﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;

namespace GrainManage
{
    public class SQLite
    {
        static SQLite()
        {
            ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
        }

        /// <summary>
        /// ConnectionString样例：Data source=Test.db3;Pooling=true;FailIfMissing=false
        /// </summary>
        public static string ConnectionString { get; private set; }

        private static void PrepareCommand(SQLiteCommand cmd, params object[] parameters)
        {
            if (parameters != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    var parameter = cmd.CreateParameter();
                    parameter.Value = parameters[i];
                    cmd.Parameters.Add(parameter);
                }
            }

            if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
        }

        public static DataSet ExecuteQuery(string cmdText, params object[] parameters)
        {
            DataSet ds = new DataSet();
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand command = new SQLiteCommand(cmdText, conn);
                PrepareCommand(command, parameters);
                SQLiteDataAdapter da = new SQLiteDataAdapter(command);
                da.Fill(ds);
            }
            return ds;
        }

        public static object ExecuteScalar(string cmdText, params object[] parameters)
        {
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand command = new SQLiteCommand(cmdText, conn);
                PrepareCommand(command, parameters);
                return command.ExecuteScalar();
            }
        }

        public static int Execute(string cmdText, params object[] parameters)
        {
            using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                SQLiteCommand command = new SQLiteCommand(cmdText, conn);
                PrepareCommand(command, parameters);
                return command.ExecuteNonQuery();
            }
        }

        public static SQLiteDataReader ExecuteReader(string cmdText, params object[] parameters)
        {
            using (SQLiteCommand command = new SQLiteCommand(cmdText, new SQLiteConnection(ConnectionString)))
            {
                PrepareCommand(command, parameters);
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
    }
}
